<template>
  <div>
    <div style="position: absolute; z-index: 9999;">
      <butt></butt>
    </div>
    <el-card class="box-card">
      <div slot="header" class="clearfix" ref="targetLocation">
        <span>{{taskdata.assessName }}</span>
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            ({{phaseLabel}})
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="early">初期</el-dropdown-item>
            <el-dropdown-item command="middle">中期</el-dropdown-item>
            <el-dropdown-item command="last">末期</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div>
        <el-row>
          <el-col :span="24">
            <h3 class="h2Bold" style="margin-bottom: 30px">基本情况</h3>
          </el-col>
          <el-col :span="24">
            <div style="width: 90%;margin: auto">
              <el-descriptions :column="4" border>
                <el-descriptions-item label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    姓名
                  </template>
                  {{ patientName }}
                </el-descriptions-item>
                <el-descriptions-item label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    性别
                  </template>
                  {{ gender }}
                </el-descriptions-item>
                <el-descriptions-item label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    年龄
                  </template>
                  {{ patientAge }}
                </el-descriptions-item>
                <el-descriptions-item label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    身份证号
                  </template>
                  {{ patientIdentityNo }}
                </el-descriptions-item>
                <el-descriptions-item :span="4" label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    病情摘要
                  </template>
                  {{ illnessSummary }}
                </el-descriptions-item>
                <el-descriptions-item :span="4" label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    既往史
                  </template>
                  {{ preHistory }}
                </el-descriptions-item>
                <el-descriptions-item :span="4" label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    诊断
                  </template>
                  {{ preDiagnose }}
                </el-descriptions-item>
                <el-descriptions-item :span="2" label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    评定人
                  </template>
                  {{ assessDoctor }}
                </el-descriptions-item>
                <el-descriptions-item :span="2" label-style="color:black;background:#f9f9f9" content-style="color:black;">
                  <template slot="label">
                    评定日期
                  </template>
                  {{ assessTime }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>

          <el-col>
            <div v-for="(item,index) in comList" :key="index">
              <h3 class="h2Bold">{{ item.titleName }}</h3>
              <div class="containerClass">
                <el-row v-for="(assname,index) in item.assConfig" :key="index"  :assname="assname">
                  <el-col :span="22" :offset="1">
                    <keep-alive>
                      <component
                        :is="assname"
                        ref="com"
                      ></component>
                    </keep-alive>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-card class="box-card">
      <div>
        <h3>推荐治疗方案</h3>
        <el-row :gutter="24" type="flex">
          <el-col :span="19" :offset="1">
            <div style="height: 100%;">
              <el-input type="textarea" :rows="3" placeholder="请输入" class="custom-input" v-model="recommendScheme"></el-input>
            </div>
          </el-col>
          <el-col :span="3">
            <div style="height: 100%;position: relative;">
              <el-button type="primary" @click.once="calculate_recommend" style="position: absolute;bottom:0;">智能帮写</el-button>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="1">
            <div v-if="showRecommend" class="recommend_container">
              <el-table
                v-loading="recommendLoading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.7)"
                stripe
                border
                :data="recommendData">
                <el-table-column type="index" width="50" label="序号"></el-table-column>
                <el-table-column prop="recommend" label="推荐治疗方案" ></el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button type="text" @click="use_recommend(scope.row)">应用</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-footer style="display: flex;justify-content: center;">
      <el-button @click="save" style="height:40px;background:#fa964a;color: #FFFFFF; ">暂存</el-button>
      <el-button type="primary" @click="submitForm" style="height:40px ">提 交</el-button>
      <el-button @click="cancel" style="height:40px ">取 消</el-button>
    </el-footer>
  </div>
</template>

<script>

import {addData, listData, updateData} from "@/api/gaoxin/data";
import {formatDate} from "@/utils";
import {listPatient} from "@/api/gaoxin/patient";
import {getTask, listAllAssessedTask, listTask, updateTask} from "@/api/gaoxin/taskdata";
import {listClinic} from "@/api/gaoxin/clinic";
import butt from "@/components/Drawer/butt.vue";
import bus from "@/utils/eventBus";
import axios from "axios";

const lamejs = require('lamejs')
export default {
  name: "index",
  components: {butt},
  data() {
    return {
      recommendData: [],
      patientId:'',
      clinicId:'',
      //任务数据
      taskdata: {},
      phase:'',
      recommendScheme:'',
      phaseLabel: '评定阶段',
      phaseCount: '',
      //患者基本、就诊信息
      // dataList: {},
      patientBasicInfo: {},
      patientName: '',
      patientGender: '',
      patientAge: 0,
      patientIdentityNo: '',
      patientClinicInfo: {},
      department: '',
      illnessSummary: '',
      preHistory: '',
      preDiagnose: '',
      assessDoctor: '',
      //组件列表
      comList: [],
      // 评估表数据
      assess: {},
      formData: [],
      auditOpinion: '',
      //评估数据
      pgForm: "",
      // 查询参数
      queryParams: {
        pageSize: 10,
        patientName: null,
        masterName: null,
        doctorName: null,
        assessName: null,
        phase: null,
        status: null,
        createTime: null,
        clinicId: null,
      },
      //基本信息查询参数
      queryBasicParams: {
        patientId: null
      },
      title: '',
      loading: false,
      auditOnOff: '',
      showRecommend:false,
      recommendLoading:true,
      basicRecommendations:[ //当推荐的方案数量不足3条时备用
        { recommend: '建议患者积极配合医生的治疗方案，包括药物治疗、康复训练和生活方式改变等。建议患者在医生的指导下进行适度的运动，以促进康复和改善身体功能。' },
        { recommend: '患者日常生活需要一定程度的帮助。建议提供适当的康复训练，包括物理治疗、职业治疗等，以提高患者的功能和独立性。同时，家人或护理人员可以提供必要的支持和帮助。' },
        { recommend: '建议患者接受适当的医疗护理、康复训练和生活支持，以提高生活质量、促进功能恢复和保持健康。同时，与医生和专业人士保持密切联系，根据具体情况调整和优化治疗方案。' }
      ],
    }
  },
  beforeDestroy() {
    bus.$off('watch1')
  },
  created() {

    bus.$on('watch1',()=>{
      bus.$emit('assessDetail',this.$route.name)
    })
    this.getConfigKey("gx.audit.auditOnOff").then(response => {
      this.auditOnOff = response.msg;
    });
    const taskId = Number(this.$route.params.id);
    getTask(taskId).then(response => {
      this.taskdata = response.data;
      // console.log(this.taskdata)
      this.queryBasicParams.patientId = this.taskdata.patientId;
      this.assessDoctor = this.taskdata.doctorName
      this.phase=this.taskdata.phase
      this.getBasicData();
      this.getClinicData();
      let assessConfig = this.taskdata.assessConfig;
      this.comList = JSON.parse(this.taskdata.assessConfig);

      //审核不通过或者暂存
      if (this.taskdata.status == 4 || this.taskdata.status == 5) {
        listData({taskId: this.taskdata.taskId}).then(response => {
          const taskData = response.rows;
          this.formData[0] = taskData[0];
          this.recommendScheme=this.formData[0].recommendScheme
          var temp1=this.formData[0].assessData;
          let replaceAfter = temp1.toString();
          this.formData[0].assessData=JSON.parse(replaceAfter);
          let k = 0;
          for (let i = 0; i < this.comList.length; i++) {
            this.comList[i].assConfig.forEach(item => {
              let assname = item;
              this.$refs.com[k++].pgForm = this.formData[0].assessData[assname];
            });
          }
          if (this.taskdata.status == 5) {//审核不通过
            this.title = "审核意见";
            this.auditOpinion = this.formData[0].auditOpinion;
            this.openAuditOpinion();
          }
        });
      }
    });

  },
  computed: {
    gender(){
      if(this.patientGender === '0') return '男'
      if(this.patientGender === '1') return '女'
      if(this.patientGender === '2') return '未知'
    },
    assessTime(){
      const timeOne = new Date()
      const year = timeOne.getFullYear()
      let month = timeOne.getMonth() + 1
      let day = timeOne.getDate()
      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
      const NOW_MONTHS_AGO = `${year}-${month}-${day}`
      return NOW_MONTHS_AGO
    }
  },
  watch: {
    phase(val) {
      if(val === '1') {
        listAllAssessedTask({
          patientId: this.taskdata.patientId,
          assessId: this.taskdata.assessId,
          phase: '1'
        }).then(response => {
          this.phaseCount = response.rows.length + 1;
        });
      }
      else if(val === '2') {
        listAllAssessedTask({
          patientId: this.taskdata.patientId,
          assessId: this.taskdata.assessId,
          phase: '2'
        }).then(response => {
          this.phaseCount = response.rows.length + 1;
        });
      }
      else {
        listAllAssessedTask({
          patientId: this.taskdata.patientId,
          assessId: this.taskdata.assessId,
          phase: '3'
        }).then(response => {
          this.phaseCount = response.rows.length + 1;
        });
      }
    }
  },
  methods: {
    openAuditOpinion() {
      const h = this.$createElement;
      let auditOpinion = this.auditOpinion;
      // console.log(auditOpinion)
      let html = h('p', null, [
        h('div', [
          h('div',auditOpinion), // 传变量
        ], null),
      ])
      this.$notify({
        title: '审核意见',
        message: html,
        type: 'warning',
        duration: 0
      });
    },
    //查询患者基本信息
    getBasicData(){
      this.loading = true;
      listPatient(this.queryBasicParams).then(response => {
        this.patientBasicInfo = response.rows;
        this.patientId=this.patientBasicInfo[0].patientId
        this.patientName = this.patientBasicInfo[0].patientName;
        this.patientGender = this.patientBasicInfo[0].patientGender;
        this.patientAge = this.patientBasicInfo[0].patientAge;
        this.patientIdentityNo = this.patientBasicInfo[0].patientIdentityNo;
        this.loading = false;
      });
    },
    //查询患者就诊信息
    getClinicData(){
      listClinic(this.queryBasicParams).then(response => {
        this.patientClinicInfo = response.rows;
        const last = this.patientClinicInfo.length - 1;
        this.clinicId=this.patientClinicInfo[last].clinicId
        this.department = this.patientClinicInfo[last].department
        this.preDiagnose = this.patientClinicInfo[last].preDiagnose
        this.illnessSummary = this.patientClinicInfo[last].illnessSummary
        this.preHistory = this.patientClinicInfo[last].preHistory
      });
    },
    //取消
    cancel() {
      this.$tab.closePage()
      this.$router.go(-1);
    },

    //将JSON对象转化为JSON字符串
    toJsonString(){
      var pgform = {};
      let temp = 0;
      console.log(this.comList)
      this.comList.forEach(item => {
        for (const x in item.assConfig) {
          var t = this.$refs.com[temp++].pgForm;
          pgform[item.assConfig[x]] = t;
        }
      });
      return JSON.stringify(pgform);
    },
    /** 暂存按钮 **/
    save() {
      //如果pgForm是空的话，就执行一下，如果不是空，说明智能推荐的时候已经执行过了，
      if(!this.pgForm){
        this.pgForm=this.toJsonString();
      }
      const taskId = this.taskdata.taskId;

      if (this.taskdata.status == 1) {
        addData({
          assessData: this.pgForm,
          taskId: this.taskdata.taskId,
          phase: this.phase,
          status: 4,
          recommendScheme:this.recommendScheme
        }).then(response => {
          this.$modal.msgSuccess("暂存成功");
          updateTask({taskId:taskId,status: 4,phase:this.phase})
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        });
      }
      else {
        this.formData[0].assessData = this.pgForm;
        this.formData[0].phase = this.phase;
        this.formData[0].recommendScheme = this.recommendScheme;
        let form = {};
        form = this.formData[0]
        form.status=4
        updateData(form).then(response => {
        }).then(response => {
          this.$modal.msgSuccess("暂存成功");
          updateTask({taskId:taskId,status: 4,phase:this.phase})
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        });
      }
    },
    /** 提交按钮 */
    submitForm () {
      if(this.phase === null) {
        this.$message.warning('请选择评定阶段！')
        const targetLocation=this.$refs.targetLocation;
        targetLocation.scrollIntoView();
        return
      }
      //如果pgForm是空的话，就执行一下，如果不是空，说明智能推荐的时候已经执行过了，
      if(!this.pgForm){
        this.pgForm=this.toJsonString();
      }
      const taskId = this.taskdata.taskId;

      if (this.auditOnOff == 'false') {
        if (this.taskdata.status == 1) {
          addData({
            assessData: this.pgForm,
            taskId: this.taskdata.taskId,
            phase: this.phase,
            createTime: formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
            status: 3,
            recommendScheme:this.recommendScheme
          }).then(response => {
            this.$modal.msgSuccess("提交成功");
            updateTask({taskId:taskId,status: 3,phase:this.phase,phaseCount:this.phaseCount})
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        }
        else {
          this.formData[0].assessData = this.pgForm;
          this.formData[0].status = 2;
          this.formData[0].phase = this.phase;
          this.formData[0].recommendScheme = this.recommendScheme;
          this.formData[0].createTime = formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
          let form = {};
          form = this.formData[0];
          updateData(form).then(response => {
          }).then(response => {
            this.$modal.msgSuccess("提交成功");
            updateTask({taskId:taskId,status: 3,phase:this.phase,phaseCount:this.phaseCount})
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        }
      } else {
        if (this.taskdata.status == 1) {
          addData({
            assessData: this.pgForm,
            taskId: this.taskdata.taskId,
            phase: this.phase,
            recommendScheme:this.recommendScheme,
            createTime: formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
            status: 2
          }).then(response => {
            this.$modal.msgSuccess("提交成功");
            updateTask({taskId:taskId,status: 2,phase:this.phase,phaseCount:this.phaseCount})
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        }
        else {
          this.formData[0].assessData = this.pgForm;
          this.formData[0].status = 2;
          this.formData[0].phase = this.phase;
          this.formData[0].recommendScheme = this.recommendScheme;
          this.formData[0].createTime = formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
          let form = {};
          form = this.formData[0];
          updateData(form).then(response => {
          }).then(response => {
            this.$modal.msgSuccess("提交成功");
            updateTask({taskId:taskId,status: 2,phase:this.phase,phaseCount:this.phaseCount})
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        }
      }
    },
    handleCommand(command) {
      switch (command) {
        case "early":
          this.phase = '1';
          this.phaseLabel = "初期";
          break;
        case "middle":
          this.phase = '2';
          this.phaseLabel = "中期";
          break
        case "last":
          this.phase = '3';
          this.phaseLabel = "末期";
          break
      }
    },

    calculate_recommend(){
      this.showRecommend=true;
      this.pgForm=this.toJsonString();
      const formData = new FormData()
      formData.append('file', this.pgForm)
      const axios = require('axios')
      axios.post("http://127.0.0.1:5001/similarity", formData).then(res => {
        this.recommendData=res.data;
        // 判断返回的结果数量是否小于3
        if (this.recommendData.length < 3) {
          // 计算需要补充的推荐方案数量
          const missingCount = 3 - this.recommendData.length;
          // 从准备好的基础推荐方案数组中补充缺少的推荐方案
          const additionalRecommendations = this.basicRecommendations.slice(0, missingCount);
          // 将补充的推荐方案添加到返回的结果中
          this.recommendData.push(...additionalRecommendations);
        }
        this.recommendLoading=false;
      }).catch((error) => {
        console.log('获取数据失败', error)
      })
    },
    //应用
    use_recommend(row){
      this.recommendScheme=row.recommend
    }
  },


}
</script>

<style scoped>
.tools{
  /*background-color: rebeccapurple;*/
  /*width: 100px;*/
  /*height: 100px;*/
  position:fixed;
  right: 10px;
  bottom:200px;
  z-index: 999;
}

.box-card{
  width: 78%;
  margin: 30px auto;
  letter-spacing:0.1em;
}
.clearfix {
  font-size: 32px;
  font-weight: 500;
  text-align: center;
}
.h2Bold {
  font-weight: 600;
  margin: 30px 0 0 0;
}
.basicCondition .el-row{
  margin-bottom: 20px;
}
.containerClass {
  min-height: 80px;
  /*padding: 20px 0;*/
}
.el-radio /deep/ .el-radio__label{
  font-size: 20px !important;
}

.el-dropdown-link {
  font-size: 20px;
  margin-left: 20px;
  cursor: pointer;
  color: #409EFF;
}

.recommend_container {
  width: 78%;
  padding: 30px 0 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.custom-input ::v-deep .el-textarea__inner {
  border-color: #333; /* 设置边框颜色为深灰色 */
}


</style>

